<template>
  <div class="home-container">
    <Header />
    <div class="content">
      <!-- 搜索表单 -->
      <Form :model="searchForm" ref="searchForm">
        <FormItem label="绘本名称" prop="name">
          <Input v-model="searchForm.name" placeholder="请输入绘本名称" />
        </FormItem>
        <Button type="primary" @click="searchBooks">搜索</Button>
        <Button type="success" style="margin-left: 10px" @click="addBook">新建绘本</Button>
      </Form>
      
      <!-- 绘本表格 -->
      <Table :columns="columns" :data="tableData">
        <!-- 图片列自定义渲染 -->
        <template slot-scope="{ row }" slot="image">
          <img :src="getImageUrl(row.image_url)" alt="绘本图片" class="book-image" />
        </template>
        
        <!-- 操作列 -->
        <template slot-scope="{ row, index }" slot="action">
          <Button type="primary" style="margin-right: 5px" @click="editBook(index)">编辑</Button>
          <Button type="error" @click="deleteBook(index)">删除</Button>
        </template>
      </Table>
      
      <!-- 分页 -->
      <Page
        :total="total"
        :page-size="pageSize"
        @on-change="handlePageChange"
        v-if="total > pageSize"
      />
    </div>
    
    <!-- 编辑/新建绘本弹窗 -->
    <Drawer
      :title="drawerTitle"
      v-model="isShow"
      width="800"
      :mask-closable="false"
    >
      <Form :model="editForm" ref="editForm" :rules="formRules">
        <FormItem label="绘本名称" prop="name">
          <Input v-model="editForm.name" placeholder="请输入绘本名称" />
        </FormItem>
        <FormItem label="英文内容" prop="content_en">
          <Input v-model="editForm.content_en" type="textarea" placeholder="请输入英文内容" />
        </FormItem>
        <FormItem label="封面图片" prop="image_url">
          <Upload
            :action="uploadUrl"
            :headers="uploadHeaders"
            :on-success="handleUploadSuccess"
            :format="['jpg','jpeg','png']"
            :max-size="2048"
            :data="{ folder: 'books' }"
          >
            <Button icon="ios-cloud-upload-outline">上传图片</Button>
          </Upload>
          <div v-if="editForm.image_url" class="preview-image">
            <img :src="getImageUrl(editForm.image_url)" alt="预览" />
          </div>
        </FormItem>
        
        <!-- 内容编辑表格 -->
        <h3 style="margin: 20px 0">绘本内容</h3>
        <Table :columns="contentColumns" :data="editForm.content" border>
          <template slot-scope="{ row, index }" slot="image">
            <Upload
              :action="uploadUrl"
              :headers="uploadHeaders"
              :on-success="(response) => handleContentImageUpload(response, index)"
              :format="['jpg','jpeg','png']"
              :max-size="2048"
              :data="{ folder: 'books' }"
            >
              <Button icon="ios-cloud-upload-outline">上传图片</Button>
            </Upload>
            <div v-if="row.image" class="preview-image">
              <img :src="getImageUrl(row.image)" alt="内容图片预览" style="max-width: 100px; max-height: 80px" />
            </div>
          </template>
          <template slot-scope="{ row, index }" slot="action">
            <Button type="primary" size="small" style="margin-right: 5px" @click="editContent(index)">编辑</Button>
            <Button type="error" size="small" @click="deleteContent(index)">删除</Button>
          </template>
        </Table>
        <Button type="dashed" style="width: 100%; margin: 10px 0" @click="addContent">添加内容</Button>
      </Form>
      
      <div class="drawer-footer">
        <Button type="primary" @click="saveBook" :loading="saving">保存</Button>
        <Button type="default" @click="cancelEdit" style="margin-left: 8px">取消</Button>
      </div>
    </Drawer>
    
    <Footer />
  </div>
</template>

<script>
import Header from '@/components/Header';
import Footer from '@/components/Footer'; 
import store from '../store';
import { 
  formatTime,
  formatDate
} from '@/utils/valid';
import { 
  getBookList,
  addBook,
  editBook,
  deleteBook,
  uploadFile
} from '@/utils/api';
import { uploadUrl } from '@/utils/url';

export default {
  components: {
    Header,
    Footer
  },
  data() {
    return {
      searchForm: { name: '' },
      columns: [
        { title: '绘本名称', key: 'name' },
        { title: '英文内容', key: 'content_en' },
        { title: '封面图片', slot: 'image' },
        { title: '操作', slot: 'action' }
      ],
      contentColumns: [
        { title: '标题', key: 'title' },
        { title: '内容', key: 'content' },
        { title: '英文内容', key: 'english_content' },
        { title: '图片', slot: 'image' },
        { title: '操作', slot: 'action' }
      ],
      tableData: [],
      total: 0,
      pageSize: 10,
      isShow: false,
      drawerTitle: '新建绘本',
      editForm: {
        id: 0,
        name: '',
        content_en: '',
        image_url: '',
        content: []
      },
      formRules: {
        name: [
          { required: true, message: '绘本名称不能为空', trigger: 'blur' }
        ],
        content_en: [
          { required: true, message: '英文内容不能为空', trigger: 'blur' }
        ],
        image_url: [
          { required: true, message: '请上传封面图片', trigger: 'change' }
        ]
      },
      uploadUrl: uploadUrl,
      uploadHeaders: {
        'Authorization': `Bearer ${store.state.token}`
      },
      saving: false,
      currentEditIndex: -1,
      currentContentEditIndex: -1
    };
  },
  created() {
   
  },
  mounted() {
  	 // this.loadBooks();
  },
  methods: {
    // 获取图片的完整URL
    getImageUrl(relativePath) {
      if (!relativePath) return '';
      return relativePath.startsWith('http') ? relativePath : `${uploadUrl}${relativePath}`;
    },
    
    // 加载绘本列表
    loadBooks() {
      this.$Spin.show();
      getDrawList({
        name: this.searchForm.name,
        page: this.pageNo,
        pageSize: this.pageSize
      })
      .then(res => {
        if (res.code === 0) {
          this.tableData = res.data.rows || [];
          this.total = res.data.total || 0;
        } else {
          this.$Message.error(res.msg || '获取绘本列表失败');
        }
      })
      .finally(() => {
        this.$Spin.hide();
      });
    },
    
    // 搜索绘本
    searchBooks() {
      this.pageNo = 1;
      this.loadBooks();
    },
    
    // 新建绘本
    addBook() {
      this.drawerTitle = '新建绘本';
      this.currentEditIndex = -1;
      this.editForm = {
        id: 0,
        name: '',
        content_en: '',
        image_url: '',
        content: []
      };
      this.isShow = true;
      this.$nextTick(() => {
        this.$refs.editForm.resetFields();
      });
    },
    
    // 编辑绘本
    editBook(index) {
      this.drawerTitle = '编辑绘本';
      this.currentEditIndex = index;
      const book = this.tableData[index];
      this.editForm = {
        id: book.id,
        name: book.name,
        content_en: book.content_en,
        image_url: book.image_url,
        content: book.content || []
      };
      this.isShow = true;
    },
    
    // 删除绘本
    deleteBook(index) {
      this.$Modal.confirm({
        title: '确认删除',
        content: '确定要删除该绘本吗？',
        onOk: () => {
          const book = this.tableData[index];
          deleteBook(book.id)
            .then(res => {
              if (res.code === 0) {
                this.$Message.success('删除成功');
                this.tableData.splice(index, 1);
                this.total = Math.max(this.total - 1, 0);
              } else {
                this.$Message.error(res.msg || '删除失败');
              }
            });
        }
      });
    },
    
    // 保存绘本
    saveBook() {
      this.$refs.editForm.validate(valid => {
        if (!valid) return;
        
        this.saving = true;
        const formData = {
          name: this.editForm.name,
          content_en: this.editForm.content_en,
          image_url: this.editForm.image_url,
          content: this.editForm.content
        };
        
        if (this.editForm.id > 0) {
          // 编辑
          editBook(this.editForm.id, formData)
            .then(res => {
              if (res.code === 0) {
                this.$Message.success('编辑成功');
                this.updateTableData();
              } else {
                this.$Message.error(res.msg || '编辑失败');
              }
            })
            .finally(() => {
              this.saving = false;
            });
        } else {
          // 新建
          addBook(formData)
            .then(res => {
              if (res.code === 0) {
                this.$Message.success('新建成功');
                this.editForm.id = res.data.id;
                this.updateTableData();
              } else {
                this.$Message.error(res.msg || '新建失败');
              }
            })
            .finally(() => {
              this.saving = false;
            });
        }
      });
    },
    
    // 更新表格数据
    updateTableData() {
      if (this.currentEditIndex >= 0 && this.currentEditIndex < this.tableData.length) {
        // 更新现有记录
        this.$set(this.tableData, this.currentEditIndex, {
          ...this.tableData[this.currentEditIndex],
          ...this.editForm
        });
      } else {
        // 添加新记录
        this.tableData.unshift({
          ...this.editForm
        });
        this.total++;
      }
      this.isShow = false;
    },
    
    // 取消编辑
    cancelEdit() {
      this.isShow = false;
    },
    
    // 处理封面图片上传成功
    handleUploadSuccess(response, file, fileList) {
      if (response.code === 0) {
        this.editForm.image_url = response.data.path;
      } else {
        this.$Message.error(response.msg || '上传失败');
      }
    },
    
    // 处理内容图片上传成功
    handleContentImageUpload(response, index) {
      if (response.code === 0) {
        this.editForm.content[index].image = response.data.path;
      } else {
        this.$Message.error(response.msg || '上传失败');
      }
    },
    
    // 添加内容
    addContent() {
      this.editForm.content.push({
        title: '',
        content: '',
        english_content: '',
        image: ''
      });
    },
    
    // 编辑内容
    editContent(index) {
      // 这里可以根据需要实现更复杂的内容编辑逻辑
      this.currentContentEditIndex = index;
    },
    
    // 删除内容
    deleteContent(index) {
      this.editForm.content.splice(index, 1);
    },
    
    // 分页切换
    handlePageChange(page) {
      this.pageNo = page;
      this.loadBooks();
    }
  }
};
</script>

<style scoped>
.book-image {
  width: 80px;
  height: 100px;
  object-fit: cover;
  border-radius: 4px;
}

.preview-image {
  margin-top: 10px;
  text-align: center;
}

.preview-image img {
  max-width: 200px;
  max-height: 150px;
  border-radius: 4px;
}

.drawer-footer {
  text-align: right;
  margin-top: 20px;
}
</style>